package com.yc.vote.mapper;

import com.yc.vote.entity.TpVote;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * <p>
 * 投票系统-题目表-2 Mapper 接口
 * </p>
 *
 * @author baomidou
 * @since 2023-07-10
 */
public interface TpVoteMapper extends BaseMapper<TpVote> {

    @ResultMap("rm1") // resultMap="rm1"
    @Select("select a.*," +
            " (select count(*) from tp_record b where a.id=b.vid and b.usid=#{uid}) voted" +
            " from tp_vote a")
    List<TpVote> select(TpVote vote, @Param("uid") String uid);

    // @Results => <resultMap id="rm1">
    // @Result => <result>
    // id = true => <id>
    // @Many => <collection>
    @Results(
        id="rm1",
        value = {
            @Result(column = "id", property = "id", id = true),
            @Result(
                column = "id", property = "items",
                many = @Many(
                    select = "com.yc.vote.mapper.TpItemsMapper.selectByVid"
                )
            ),
            @Result(
                column = "id", property = "users",
                one = @One(
                    select = "selectUsers"
                )
            )
        }
    )
    @Select("select a.*," +
            " (select count(*) from tp_record b where a.id=b.vid and b.usid=#{uid}) voted" +
            " from tp_vote a where id=#{id}")
    TpVote selectById(@Param("id") String id, @Param("uid") String uid);

    @Insert("insert into tp_vote values (default, " +
            "#{vname},#{vtype},now(),null)")
    @Options(useGeneratedKeys = true, keyColumn = "id",
             keyProperty = "id")
    int insert(TpVote vote);

    @Select("select count(distinct usid) from tp_record where vid=#{vid} group by vid")
    int selectUsers(String vid);
}
